<script setup>
import { ref,nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { getToken } from "@/utils/auth";

import OSS from "ali-oss"
const props = defineProps({
    //上传提示语
    tips:{
        default:"",
        type:String
    },
    //上传类型限制
    videoType:{
        default:['video/mp4'],
        type:Array
    },
    //上传大小限制
    videoSize:{
        default:100 * 1024 * 1024,
        type:Number
    },
    //最大上传数量
     maxVideoLength:{
        default:1,
        type:Number
    },
    videoInfo:{
      default:"",
      type:String
    },
    action:{
        default:"/gateway/jy-system/file/uploadOssFile",
        type:String
    },
    requestHeaders:{
        default:{
            Authorization: `Bearer ${getToken()}`,
        },
        type:Object
    },
})
const baseUrl = import.meta.env.VITE_APP_UPLOADURL;
const emit = defineEmits(["backValue"])
const uploadPercentage = ref(0);
const videoList= ref([]);
const videoLoading = ref(false);
const UploadLoading = ref(false)
if(((props.videoInfo??'') !== '') && (props.videoInfo != '-')){
    videoList.value.push(props.videoInfo)
}
const handleBeforeUploadVideoUrl = (file)=>{
    if(!(props.videoType.indexOf(file.type) != -1)){
        ElMessage({
            message: '请上传正确视频格式',
            type: 'warning'
        });
        return false;
    }
    if(file.size > props.videoSize){
        ElMessage({
            message: '视频上传过大',
            type: 'warning'
        });
        return false;
    }
    UploadLoading.value = true
    return true
};
const handleAvatarSuccess = (response,uploadFile) => {
    console.log(response,uploadFile,'response,uploadFile');
    if(response.code == 0){
        let url = response?.data?.fileUrl || ''
        videoList.value.push(url);
        emit("backValue",videoList.value);
   
    }else{
        ElMessage.error('上传失败') 
    }
    UploadLoading.value = false
}
const handleFileError = (response)=>{
    ElMessage.error('上传失败') 
    UploadLoading.value = false
}
const handleRequest = async (param)=>{
    let file = param.file;
    let client = new OSS({
        // // region以杭州为例（oss-cn-hangzhou），其他region按实际情况填写。
        // region: "<Your region>",
        // // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录RAM控制台创建RAM账号。
        // accessKeyId: "<Your AccessKeyId>",
        // accessKeySecret: "<Your AccessKeySecret>",
        // bucket: "Your bucket name",
        region: "oss-cn-hangzhou",
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录RAM控制台创建RAM账号。
        accessKeyId: "LTAI5tBywHDSaqpsrjBVycnr",
        accessKeySecret: "Ffp2jJJIPqsDSGEmM3iMgtVJaxNCQJ",
        bucket: "jwkj-videos",
    });
    try {
        // object-key可以自定义为文件名（例如file.txt）或目录（例如abc/test/file.txt）的形式，实现将文件上传至当前Bucket或Bucket下的指定目录。
        let nowDate = new Date().getTime();
        let fileName = nowDate.toString() + (parseInt(Math.random()*10));
        videoLoading.value = true;
        uploadPercentage.value = 0;
        client
        .multipartUpload(`${fileName}.mp4`, file, {
            progress: function (p) {
                let percentage = p * 100;
                uploadPercentage.value = Number(percentage.toFixed(2));

            },
            // headers: {
            //   // 设置上传回调
            //   "x-oss-callback": result.callback,
            //   "x-oss-callback-var": result["callback-var"],
            // },
        })
        .then((result) => {

            const url =
            result.res.requestUrls.length > 0
                ? result.res.requestUrls[0].split("?")[0]
                : "";
            videoList.value.push(url);
            emit("backValue",videoList.value);
            videoLoading.value = false;
        })
        .catch((err) => {
            videoLoading.value = false;
            /**
             * 设置本地上传失败的回调
             */
        });
    } catch (e) {
        console.log(e);
    }
};
const removeVideo = (index)=>{
    videoList.value.splice(index,1)
    emit("backValue",videoList.value);
}

</script>
<template>

    <div class="video-area">
        <div class="video-avatar-area" v-if="videoList.length < maxVideoLength">
            <el-upload
            class="video-avatar-uploader"
            :action="baseUrl + action"
            :headers="requestHeaders"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="handleBeforeUploadVideoUrl"
            v-loading="UploadLoading"
            accept=".mp4"
            :on-error="handleFileError"
     
            >
                <img src="@/assets/images/plus-img.png" alt="" style="width: 40px;height: 40px;">
                <template #tip >
                    <div style="color:#999;line-height:20px;;font-size:12px;width:100%;text-align:center" v-if="tips">
                        {{ tips }}
                    </div>
                </template>
            </el-upload>  
            <div class="video-div-hold" v-if="videoLoading">
                <el-progress type="dashboard" :percentage="uploadPercentage" :width="180" :stroke-width="10">
                    <template #default="{ percentage }">
                      <span class="percentage-value">{{ percentage }}%</span>
                      <span class="percentage-label">视频上传中</span>
                    </template>
                  </el-progress>
            </div>
        </div> 
        <div class="video" v-for="(item,index) in videoList" :key="index">
            <div class="video-show">
                <video :src="item" controls></video>
                <div class="close">
                    <img src="@/assets/images/black_guanbi.png" alt="" @click.stop="removeVideo(index)">
                </div>
            </div>
            <!-- <div class="menu">
                <el-tooltip
                    class="box-item"
                    effect="dark"
                    content="删除视频"
                    placement="bottom"
                >
                <el-icon style="cursor:pointer;margin-top:5px;font-size:20px" @click="removeVideo(index)"><Delete /></el-icon>
              </el-tooltip>
                
            </div> -->
        </div>
    </div>

</template>
<style lang="less" scoped>
@globalWidth:380px;
@globalHeight:214px;
.video-avatar-area{
    width: @globalWidth;
    height: @globalHeight;
    margin-right: 16px;
}
.close {
    position: absolute;
    right: 10px;
    top: 7px;
    img {
      width: 18px;
      height: 18px;
      cursor: pointer;

    }
}
.video-area{
    width: 100%;
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
    
    .video{
        margin-right:16px;
        margin-bottom:20px;
        width: @globalWidth;
        height: @globalHeight;
        position: relative;
        border-radius: 10px;
        box-sizing: border-box;


        .video-show{
            width: 100%;
            height: 100%;

            box-sizing: border-box;
            position:relative;
            video{
                width: 100%;
                height: 100%;
                border-radius: 10px;
            }
        }
        .menu{
            height: 35px;
            display: flex;
            align-items: center;
            justify-content: flex-end;
            padding:0 10px;
        }
    }
    .video-avatar-area{
        margin-right: 16px;
    }
}
.percentage-value {
    display: block;
    margin-top: 10px;
    font-size: 28px;
}
.percentage-label {
    display: block;
    margin-top: 10px;
    font-size: 12px;
}
</style>
<style lang="less">
@globalWidth:380px;
@globalHeight:214px;
.video-avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  background: #f3f3f3;
  //   width: @globalWidth;
  //   height: @globalHeight;
  width: 100%;
  height: 100%;
}
.video-avatar-uploader{
  height: 214px;
}
.video-avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-icon.video-avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  //   width: @globalWidth;
  //   height: @globalHeight;
  width: 100%;
  height: 100%;
  text-align: center;
}
.video-div-hold{
    position: relative;
    margin-right: 16px;    
    width: @globalWidth;
    height: @globalHeight;
    background: #f3f3f3;
    border: 1px dashed var(--el-border-color);
    display: flex;
    justify-content: center;
    align-items: center;

}
</style>
